use std::{borrow::Cow, time::Duration};

use axum::{routing::get, Router};

use tokio::time::timeout;
use uuid::Uuid;

use crate::error::{AppErr, EC_UNKNOWN, EC_WAIT_TIMEOUT};

use super::conn::{cbor_ok, online::ONLINE_INFO, CborRet, Void};

async fn on_create_uuid() -> CborRet<String> {
    let id = Uuid::new_v4();
    cbor_ok(id.to_string())
}

async fn on_wait_update() -> Result<Void, AppErr> {
    let mut rx = ONLINE_INFO.subscribe();
    timeout(Duration::from_secs(5), rx.recv())
        .await
        .map_err(|_| AppErr::Service(EC_WAIT_TIMEOUT, Cow::Borrowed("等待更新超时")))?
        .map_err(|_| AppErr::Service(EC_UNKNOWN, Cow::Borrowed("未知错误")))?;
    Ok(Void)
}

mod vote;
mod vote_num;

pub fn register() -> Router {
    Router::new()
        .route("/uuid", get(on_create_uuid))
        .route("/wait", get(on_wait_update))
        .nest("/vote", vote::register())
        .nest("/vote_num", vote_num::register())
}
